// PDF导出工具类
class PDFExport {
  constructor() {
    this.canvas = null
    this.ctx = null
  }

  // 初始化画布
  initCanvas(width = 595, height = 842) { // A4尺寸
    return new Promise((resolve, reject) => {
      try {
        const query = uni.createSelectorQuery()
        query.select('#pdf-canvas').fields({
          node: true,
          size: true
        }).exec((res) => {
          if (res[0]) {
            const canvas = res[0].node
            const ctx = canvas.getContext('2d')
            
            const dpr = uni.getSystemInfoSync().pixelRatio
            canvas.width = width * dpr
            canvas.height = height * dpr
            ctx.scale(dpr, dpr)
            
            this.canvas = canvas
            this.ctx = ctx
            resolve({ canvas, ctx })
          } else {
            reject(new Error('Canvas not found'))
          }
        })
      } catch (e) {
        reject(e)
      }
    })
  }

  // 绘制文本
  drawText(text, x, y, options = {}) {
    const {
      fontSize = 14,
      color = '#000000',
      fontWeight = 'normal',
      textAlign = 'left',
      maxWidth = null,
      lineHeight = 1.4
    } = options

    this.ctx.font = `${fontWeight} ${fontSize}px sans-serif`
    this.ctx.fillStyle = color
    this.ctx.textAlign = textAlign

    if (maxWidth) {
      // 文本换行处理
      const lines = this.wrapText(text, maxWidth)
      lines.forEach((line, index) => {
        this.ctx.fillText(line, x, y + (index * fontSize * lineHeight))
      })
      return lines.length * fontSize * lineHeight
    } else {
      this.ctx.fillText(text, x, y)
      return fontSize * lineHeight
    }
  }

  // 文本换行处理
  wrapText(text, maxWidth) {
    const words = text.split('')
    const lines = []
    let currentLine = ''

    for (let i = 0; i < words.length; i++) {
      const testLine = currentLine + words[i]
      const metrics = this.ctx.measureText(testLine)
      
      if (metrics.width > maxWidth && currentLine !== '') {
        lines.push(currentLine)
        currentLine = words[i]
      } else {
        currentLine = testLine
      }
    }
    
    if (currentLine) {
      lines.push(currentLine)
    }
    
    return lines
  }

  // 绘制矩形
  drawRect(x, y, width, height, options = {}) {
    const {
      fillColor = null,
      strokeColor = null,
      lineWidth = 1,
      borderRadius = 0
    } = options

    this.ctx.lineWidth = lineWidth

    if (borderRadius > 0) {
      this.drawRoundedRect(x, y, width, height, borderRadius)
    } else {
      if (fillColor) {
        this.ctx.fillStyle = fillColor
        this.ctx.fillRect(x, y, width, height)
      }
      
      if (strokeColor) {
        this.ctx.strokeStyle = strokeColor
        this.ctx.strokeRect(x, y, width, height)
      }
    }
  }

  // 绘制圆角矩形
  drawRoundedRect(x, y, width, height, radius) {
    this.ctx.beginPath()
    this.ctx.moveTo(x + radius, y)
    this.ctx.lineTo(x + width - radius, y)
    this.ctx.quadraticCurveTo(x + width, y, x + width, y + radius)
    this.ctx.lineTo(x + width, y + height - radius)
    this.ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height)
    this.ctx.lineTo(x + radius, y + height)
    this.ctx.quadraticCurveTo(x, y + height, x, y + height - radius)
    this.ctx.lineTo(x, y + radius)
    this.ctx.quadraticCurveTo(x, y, x + radius, y)
    this.ctx.closePath()
    this.ctx.fill()
  }

  // 绘制线条
  drawLine(x1, y1, x2, y2, options = {}) {
    const {
      color = '#000000',
      lineWidth = 1,
      lineDash = []
    } = options

    this.ctx.strokeStyle = color
    this.ctx.lineWidth = lineWidth
    this.ctx.setLineDash(lineDash)
    
    this.ctx.beginPath()
    this.ctx.moveTo(x1, y1)
    this.ctx.lineTo(x2, y2)
    this.ctx.stroke()
    
    this.ctx.setLineDash([]) // 重置线条样式
  }

  // 绘制图表
  drawChart(data, x, y, width, height, type = 'line') {
    if (!data || data.length === 0) return

    const padding = 40
    const chartX = x + padding
    const chartY = y + padding
    const chartWidth = width - padding * 2
    const chartHeight = height - padding * 2

    // 绘制背景
    this.drawRect(x, y, width, height, {
      fillColor: '#f8f9fa',
      strokeColor: '#e9ecef',
      borderRadius: 8
    })

    // 绘制坐标轴
    this.drawLine(chartX, chartY + chartHeight, chartX + chartWidth, chartY + chartHeight, {
      color: '#6c757d'
    })
    this.drawLine(chartX, chartY, chartX, chartY + chartHeight, {
      color: '#6c757d'
    })

    if (type === 'line') {
      this.drawLineChart(data, chartX, chartY, chartWidth, chartHeight)
    } else if (type === 'bar') {
      this.drawBarChart(data, chartX, chartY, chartWidth, chartHeight)
    }
  }

  // 绘制折线图
  drawLineChart(data, x, y, width, height) {
    if (data.length < 2) return

    const maxValue = Math.max(...data.map(d => d.value))
    const minValue = Math.min(...data.map(d => d.value))
    const valueRange = maxValue - minValue || 1

    this.ctx.strokeStyle = '#007bff'
    this.ctx.lineWidth = 2
    this.ctx.beginPath()

    data.forEach((point, index) => {
      const pointX = x + (index / (data.length - 1)) * width
      const pointY = y + height - ((point.value - minValue) / valueRange) * height

      if (index === 0) {
        this.ctx.moveTo(pointX, pointY)
      } else {
        this.ctx.lineTo(pointX, pointY)
      }

      // 绘制数据点
      this.ctx.save()
      this.ctx.fillStyle = '#007bff'
      this.ctx.beginPath()
      this.ctx.arc(pointX, pointY, 3, 0, 2 * Math.PI)
      this.ctx.fill()
      this.ctx.restore()
    })

    this.ctx.stroke()
  }

  // 绘制柱状图
  drawBarChart(data, x, y, width, height) {
    const maxValue = Math.max(...data.map(d => d.value))
    const barWidth = width / data.length * 0.8
    const barSpacing = width / data.length * 0.2

    data.forEach((item, index) => {
      const barHeight = (item.value / maxValue) * height
      const barX = x + index * (barWidth + barSpacing) + barSpacing / 2
      const barY = y + height - barHeight

      this.drawRect(barX, barY, barWidth, barHeight, {
        fillColor: '#28a745',
        borderRadius: 4
      })

      // 绘制数值标签
      this.drawText(item.value.toString(), barX + barWidth / 2, barY - 10, {
        fontSize: 12,
        textAlign: 'center',
        color: '#6c757d'
      })
    })
  }

  // 生成情绪统计报告PDF
  async generateMoodReport(data) {
    try {
      await this.initCanvas()
      
      const pageWidth = 595
      const pageHeight = 842
      let currentY = 50

      // 标题
      currentY += this.drawText('情绪统计报告', pageWidth / 2, currentY, {
        fontSize: 24,
        fontWeight: 'bold',
        textAlign: 'center',
        color: '#2c3e50'
      })

      currentY += 30

      // 报告日期
      const reportDate = new Date().toLocaleDateString('zh-CN')
      currentY += this.drawText(`报告生成日期：${reportDate}`, 50, currentY, {
        fontSize: 12,
        color: '#7f8c8d'
      })

      currentY += 40

      // 基础统计
      this.drawRect(50, currentY, pageWidth - 100, 120, {
        fillColor: '#f8f9fa',
        strokeColor: '#e9ecef',
        borderRadius: 8
      })

      currentY += 30
      currentY += this.drawText('基础统计', 70, currentY, {
        fontSize: 18,
        fontWeight: 'bold',
        color: '#2c3e50'
      })

      currentY += 10
      const stats = [
        `使用天数：${data.usageDays}天`,
        `情绪记录：${data.moodRecords}条`,
        `心理测评：${data.testCount}次`,
        `课程学习：${data.courseCount}次`
      ]

      stats.forEach(stat => {
        currentY += this.drawText(stat, 70, currentY, {
          fontSize: 14,
          color: '#34495e'
        })
      })

      currentY += 50

      // 情绪趋势图
      if (data.moodTrend && data.moodTrend.length > 0) {
        currentY += this.drawText('情绪趋势', 50, currentY, {
          fontSize: 18,
          fontWeight: 'bold',
          color: '#2c3e50'
        })

        currentY += 20
        this.drawChart(data.moodTrend, 50, currentY, pageWidth - 100, 200, 'line')
        currentY += 220
      }

      // 情绪分布
      if (data.moodDistribution && data.moodDistribution.length > 0) {
        currentY += this.drawText('情绪分布', 50, currentY, {
          fontSize: 18,
          fontWeight: 'bold',
          color: '#2c3e50'
        })

        currentY += 20
        this.drawChart(data.moodDistribution, 50, currentY, pageWidth - 100, 200, 'bar')
        currentY += 220
      }

      // 生成PDF文件
      return await this.savePDF()

    } catch (error) {
      console.error('生成PDF失败:', error)
      throw error
    }
  }

  // 保存PDF文件
  async savePDF() {
    return new Promise((resolve, reject) => {
      try {
        this.canvas.toTempFilePath({
          fileType: 'png',
          quality: 1,
          success: (res) => {
            // 将图片转换为PDF（这里简化处理，实际应用中可能需要使用专门的PDF库）
            resolve(res.tempFilePath)
          },
          fail: (error) => {
            reject(error)
          }
        })
      } catch (error) {
        reject(error)
      }
    })
  }

  // 分享PDF文件
  async sharePDF(filePath) {
    try {
      await uni.shareWithSystem({
        type: 'file',
        filePath: filePath,
        success: () => {
          uni.showToast({
            title: '分享成功',
            icon: 'success'
          })
        },
        fail: (error) => {
          console.error('分享失败:', error)
          uni.showToast({
            title: '分享失败',
            icon: 'error'
          })
        }
      })
    } catch (error) {
      console.error('分享PDF失败:', error)
      throw error
    }
  }
}

export default PDFExport